package com.ScoresSystem.controller;

import com.ScoresSystem.pojo.Score;
import com.ScoresSystem.pojo.Subject;
import com.ScoresSystem.service.ScoreService;
import com.ScoresSystem.service.SubjectService;
import com.ScoresSystem.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/score")
public class ScoreController {

    @Autowired
    ScoreService scoreService;

    @Autowired
    SubjectService subjectService;

    // 获取所有成绩
    @RequestMapping("/getAllScore")
    public Result<List<Score>> getAllScore(@RequestParam(value = "studentName", defaultValue = "") String name,
                                           @RequestParam(value = "page", defaultValue = "1") Integer page,
                                           @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        List<Score> scoreList = scoreService.getAllScore("%" + name + "%", (page - 1) * limit, limit);
        int count = scoreService.getCount("%" + name + "%");
        return new Result<>("0", "查询成功", scoreList, count);
    }

    // 添加成绩
    @RequestMapping("/addScore")
    public Result<String> addScore(Score score) {
        // 检查成绩是否存在
        Score score1 = scoreService.findScoreByStudentNoAndSubjectId(score.getStudentNo(), score.getSubjectId());
        if (score1 != null) {
            return new Result<>("1", "该学生该课程成绩已存在");
        }
        int result = scoreService.addScore(score);
        if (result == 1) {
            return new Result<>("0", "添加成功");
        } else {
            return new Result<>("1", "添加失败");
        }
    }

    // 修改成绩
    @RequestMapping("/updateScore")
    public Result<String> updateScore(Score score) {
        int result = scoreService.updateScore(score);
        if (result > 0) {
            return new Result<>("0", "修改成功");
        } else {
            return new Result<>("1", "修改失败");
        }
    }

    // 删除成绩
    @RequestMapping("/deleteScore")
    public Result<String> deleteScore(Integer id) {
        int result = scoreService.deleteScore(id);
        if (result > 0) {
            return new Result<>("0", "删除成功");
        } else {
            return new Result<>("1", "删除失败");
        }
    }

    // 获取成绩统计数据,数据格式如下
    // [['科目名称', '计算机网络', 'C语言', '计算机组成原理', '算法分析与设计'],
    // ['张三', 43.3, 85.8, 93.7, 43.3],
    // ['李四', 83.1, 73.4, 55.1, 43.3]]
    // [[科目名称, 计算机网络, C语言, 计算机组成原理, 算法分析与设计],
    // [唐伯虎, 99, 0, 0, 0],
    // [黄梦歌, 90, 78, 78, 99]]
    @RequestMapping("/getScoreAccount")
    public Result<List<List<Object>>> getScoreAccount() {
        // 结果列表
        List<List<Object>> resultList = new ArrayList<>();
        // 获取科目名称
        List<Subject> subjectList = subjectService.subjectSelect();
        List<Object> subjectNameList = new ArrayList<>();
        subjectNameList.add("科目名称");
        for (Subject subject : subjectList) {
            subjectNameList.add(subject.getName());
        }
        resultList.add(subjectNameList);
        // 获取成绩信息
        List<Score> scoreAccountList = scoreService.getScoreAccount();
        // 用于存储每个学生各科成绩的Map
        // Key: 学生姓名, Value: 各科成绩列表
        Map<String, List<Object>> studentScoreMap = new HashMap<>();
        // 初始化每个学生的成绩列表，填充0
        Set<String> studentNames = new HashSet<>();
        for (Score score : scoreAccountList) {
            studentNames.add(score.getStudentName());
        }
        for (String studentName : studentNames) {
            List<Object> scoreList = new ArrayList<>();
            scoreList.add(studentName); // 第一个位置放学生姓名
            // 初始化各科成绩为0
            for (int i = 1; i < subjectNameList.size(); i++) {
                scoreList.add(0); // 初始化为0
            }
            studentScoreMap.put(studentName, scoreList);
        }
        // 填充实际成绩数据
        for (Score score : scoreAccountList) {
            String studentName = score.getStudentName();
            String subjectName = score.getSubjectName();
            Integer studentScore = score.getScore();

            List<Object> studentScores = studentScoreMap.get(studentName);

            // 找到科目对应的位置
            for (int i = 1; i < subjectNameList.size(); i++) {
                if (subjectNameList.get(i).equals(subjectName)) {
                    // 只有当新成绩不为0或者原成绩为0时才更新
                    // 或者直接替换（如果允许多次覆盖）
                    studentScores.set(i, studentScore);
                    break;
                }
            }
        }
        // 将合并后的学生数据添加到结果列表
        resultList.addAll(studentScoreMap.values());
        //System.out.println(resultList);
        return new Result<>("0", "查询成功", resultList);
    }


    @RequestMapping("/getMyScoreInfo")
    public Result<List<Score>> getMyScore(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                          @RequestParam(value = "limit", defaultValue = "10") Integer limit, HttpSession session) {
        // 从session中获取学生信息
        String studentNo = session.getAttribute("studentNo").toString();
        List<Score> scoreList = scoreService.getMyScore(studentNo, (page - 1) * limit, limit);
        int count = scoreService.getMyScoreCount(studentNo);
        return new Result<>("0", "查询成功", scoreList, count);
    }

    @RequestMapping("/getMyScoreAccount")
    public Result<List<Score>> getMyScoreAccount(HttpSession session) {
        // 从session中获取学生信息
        String studentNo = session.getAttribute("studentNo").toString();
        List<Score> scoreList = scoreService.getMyScoreAccount(studentNo);
        return new Result<>("0", "查询成功", scoreList);
    }


}
